	import {lib,game,ui,get,ai,_status} from '../../../../noname.js'
    import {characterData} from '../../character/characterData.js'
    
    lib.init.css(lib.assetURL + 'extension/点绛唇/extension/Mvp', 'mvp');
    
    const winnerEffects={
        doudizhu: {
            win: '../../../点绛唇/extension/Mvp/animation/doudizhu_shengli',
            lose: '../../../点绛唇/extension/Mvp/animation/doudizhu_shibai'
        },
        identity: {
            zhuzhong: '../../../点绛唇/extension/Mvp/animation/SF_jiesuan_eff_zczgshengli', // 主公忠臣
            fan: '../../../点绛唇/extension/Mvp/animation/SF_jiesuan_eff_fanzeishengli', // 反贼
            nei: '../../../点绛唇/extension/Mvp/animation/SF_jiesuan_eff_neijianshengli', // 内奸
            lose: '../../../点绛唇/extension/Mvp/animation/SF_jiesuan_eff_shibai'  // 失败
        },
        default: {
            win: '../../../点绛唇/extension/Mvp/animation/unIdentity/SF_jiesuan_eff_shengli',
            lose: '../../../点绛唇/extension/Mvp/animation/unIdentity/SF_jiesuan_eff_shibai'
        }
    };

	
	get.nextNickName=function(player){
	    let randomNum = Math.floor(Math.random() * 900 + 100);
	    //const randName=['缘之空', '小小恐龙', '自然萌', '海边的ebao', '小云云', '猫猫虫', '小爱莉', '冰佬', '黎', '浮牢师', 'u', '蓝宝', '影宝', '柳下跖', '无语', '小曦', '墨渊', 'k9', '扶苏', '皇叔','倘若','辰午','小华'].randomGet();
	    let randName='小杀00'+randomNum;
	    const playName=player.nickname?player.nickname:randName;
        const nextName=player==game.me ? lib.config.connect_nickname:playName;
        if(!player.nickname)player.nickname=nextName;
        return nextName;
	};
	get.nextAvatar=function(player){
	    let headCharacter =Object.keys(lib.character).filter(key => !lib.filter.characterDisabled(key)).randomGet();
        const playHead=player.avatar?player.avatar:headCharacter;
        const nextHead=player==game.me ? lib.config.connect_avatar:playHead;
        if(!player.avatar)player.avatar=nextHead;
        return nextHead;
	};
    game.openCardsDialog = function(player) {
        const handsDialog = ui.create.div(document.body, '.handsDialog', function(event) {
            if(event.target===handsDialog)handsDialog.delete();
        });
        const cardsBg = ui.create.div('.cardsDialog', handsDialog);
        const scrollContainer = ui.create.div('.cardsScrollContainer', cardsBg);
        const cards = player.getCards('h');
        cards.forEach(function(item) {
            const card = game.createCard(
                get.name(item, false),
                get.suit(item, false),
                get.number(item, false),
                get.nature(item, false)
            );
            card.style.flex='0 0 auto';
            scrollContainer.appendChild(card);
        });
        const name = lib.translate[player.name1 + '_prefix']? `${get.prefixSpan(get.translation(player.name1 + '_prefix'), player.name1)}${get.rawName(player.name1)}`:get.translation(player.name1);
        const head = ui.create.div('.handHead', cardsBg);
        ui.create.div('.text',name + '的手牌',head);
        const image = ui.create.div('.charImage', cardsBg);
        if (characterData[player.name1]) {
            image.setBackgroundImage('extension/点绛唇/image/character/lihui/' + player.name1 + '.jpg');
        } else {
            game.getFileList('image/lihui', function(folders, files) {
                if (files.includes(player.name1 + '.jpg')) {
                    image.setBackgroundImage('image/lihui/' + player.name1 + '.jpg');
                } else {
                    image.setBackground(player.name1, 'character');
                }
            }, function() {
                image.setBackground(player.name1, 'character');
            });
        }
    };
    
	game.openMvp=function(player,callback){//打开mvp页面
	    game.mvpPlayer=player;
	    
	    game.playAudio('../extension/点绛唇/extension/Mvp/audio/mvp.mp3');
	    let skill = lib.character[player.name1].skills.randomGet();
	    let selectedAudio = game.parseSkillAudio(skill, player.name1).randomGet();
	    if(selectedAudio){
	        const actualPath = selectedAudio.startsWith("ext:")? "../extension/" + selectedAudio.slice(4): "../audio/" + selectedAudio;
	        game.playAudio(actualPath);
	    };
	    const mvpBg=ui.create.div(document.body, '.mvpBg',function(){
	        mvpBg.delete();
	        if(callback&&typeof callback==='function'){
                callback();
            };
	    }); //整个页面的大背景
	    ui.create.div('.closeText',mvpBg);
	    const mvpPlayerBg=ui.create.div('.mvpPlayerBg',mvpBg);
	    const skin=(game.qhly_getSkin&&game.qhly_getSkin(player.name1))?game.qhly_getSkin(player.name1):player.name1+'.jpg';
	    let image=new Image();
	    image.src=lib.assetURL + 'extension/千幻聆音/sanguoyuanhua/'+player.name1+'/' + skin;
	    image.onload = function() {
            mvpPlayerBg.style.backgroundSize = 'cover';
            mvpPlayerBg.style.backgroundRepeat = 'no-repeat';
            mvpPlayerBg.style.backgroundPosition = 'center center';
            if(this.width>this.height){
                mvpPlayerBg.style.width='667px';
                mvpPlayerBg.style.left='45%';
            };
            mvpPlayerBg.style.backgroundImage = `url(${image.src})`;
        };
        image.onerror = function() {
            image.onload = null;
            image.onerror = null;
            image.src=lib.assetURL + 'extension/千幻聆音/sanguoskin/'+player.name1+'/' + skin;
            image.onload = function() {
                mvpPlayerBg.style.backgroundSize = 'cover';
                mvpPlayerBg.style.backgroundRepeat = 'no-repeat';
                mvpPlayerBg.style.backgroundPosition = 'center center';
                if(this.width>this.height){
                    mvpPlayerBg.style.width='667px';
                    mvpPlayerBg.style.left='45%';
                };
                mvpPlayerBg.style.backgroundImage = `url(${image.src})`;
            }
            image.onerror = function() {
                if(characterData[player.name1]&&(!game.qhly_getSkin||!game.qhly_getSkin(player.name1))){
                    mvpPlayerBg.style.backgroundSize = '100% 100%';
                    mvpPlayerBg.style.backgroundRepeat = 'no-repeat';
                    mvpPlayerBg.style.backgroundPosition = 'center center';
                    mvpPlayerBg.style.backgroundImage=`url(${lib.assetURL + 'extension/点绛唇/image/character/bigBg/'+player.name1+'.jpg'})`;
                }else mvpPlayerBg.setBackground(player.name1,'character');
            }
        };
	    
	    var rarity = game.getRarity(player.name1);
        if (!rarity) rarity = 'junk';
	    const skinLevel=ui.create.div('.skinLevel',mvpPlayerBg);
	    var url;
        if (lib.config['extension_千幻聆音_enable']) {
            var temp;
            switch (game.qhly_getSkinLevel(player.name1, game.qhly_getSkin(player.name1), true, false)){
                case 'xiyou':
                    temp = 'rare';
                    break;
                case 'shishi':
                    temp = 'epic';
                    break;
                case 'chuanshuo':
                    temp = 'legend';
                    break;
                case 'putong':
                    temp = 'common';
                    break;
                case 'dongtai':
                    temp = 'legend';
                    break;
                case 'jueban':
                    temp = 'unique';
                    break;
                case 'xianding':
                    temp = 'restrictive';
                    break;
                default:
                    temp = 'junk';
            }
            url = lib.assetURL + 'extension/点绛唇/image/level/dc_' + temp + '.png';
        } else url = lib.assetURL + 'extension/点绛唇/image/level/dc_' + rarity + '.png';
        
        skinLevel.style.backgroundImage = 'url("' + url + '")';
        
        const name = lib.translate[player.name1 + '_prefix'] ? `${get.prefixSpan(get.translation(player.name1 + '_prefix'), player.name1)}${get.rawName(player.name1)}` : get.translation(player.name1);
        let value = '';
        let value2;
        if (lib.config['extension_千幻聆音_enable']) {
            value2 = game.qhly_getSkinInfo(player.name1, game.qhly_getSkin(player.name1), null).translation || '经典形象';
        } else value2 = '经典形象';
        value += value2 + '*' + name;
        
        ui.create.div('.name',value,mvpPlayerBg);
        
        const bestBg=ui.create.div('.bestBg',mvpPlayerBg);//全场最佳
        
        const playBg=ui.create.div('.playBg',mvpPlayerBg);
        
        const playHead=ui.create.div('.playHead',playBg);
        let headCharacter=get.nextAvatar(player);
        playHead.setBackground(headCharacter,'character');
        
        const nextName=get.nextNickName(player);
        ui.create.div('.playName',nextName,playBg);
        
        const playGuanjie=ui.create.div('.playGuanjie',playBg);
        const num=Math.floor(Math.random()*13)+1;
        if(!player.guanjie)player.guanjie=num;
        playGuanjie.setBackgroundImage('extension/点绛唇/image/level/guanjie_'+player.guanjie+'.png');
	};

	game.openOverDialog=function(winners,losers){//对局记录
	    const mvpBg=ui.create.div(document.body, '.mvpBg'); //整个页面的大背景
	    ui.create.div('.closeButton','返回',mvpBg,function(){
	        mvpBg.delete();
	    });
	    ui.create.div('.top',mvpBg);
	    ui.create.div('.bottom',mvpBg,function(){
	        if(modetop.innerHTML=='对局数据详情')updateFirst();
	        else updateSecond();
	    });
	    
	    const modetop=ui.create.div('.topBg',mvpBg);
	    
	    const createPlayerEntry = (container, playerInfo,isWin,isSecond) => {//添加玩家函数
            const node = ui.create.div('.charBg', container);
            if(playerInfo==game.me)node.setBackgroundImage('extension/点绛唇/extension/Mvp/image/meBg.png');
            if(isWin)ui.create.div('.win',node);
            if(game.mvpPlayer&&game.mvpPlayer==playerInfo)ui.create.div('.bestPlay',node);
            const identityBg = ui.create.div('.identityBg', node);
            identityBg.setBackgroundImage('extension/点绛唇/image/identity/' + playerInfo.identity + '.png');
            const touxiang = ui.create.div('.touxiang', node);
            touxiang.setBackground(playerInfo.name1, 'character');
            if(playerInfo.name2){
                const touxiang2= ui.create.div('.touxiang2', node);
                touxiang2.setBackground(playerInfo.name2, 'character');
            };
            const name = lib.translate[playerInfo.name1 + '_prefix'] ? `${get.prefixSpan(get.translation(playerInfo.name1 + '_prefix'), playerInfo.name1)}${get.rawName(playerInfo.name1)}` : get.translation(playerInfo.name1);
            let name2='';
            if(playerInfo.name2)name2=lib.translate[playerInfo.name2 + '_prefix'] ? `${get.prefixSpan(get.translation(playerInfo.name2 + '_prefix'), playerInfo.name2)}${get.rawName(playerInfo.name2)}` : get.translation(playerInfo.name2);
            ui.create.div('.name',name+(name2?'/'+name2:''),node);
            
            const nextName=get.nextNickName(playerInfo);
            ui.create.div('.playName',nextName,node);
            
            const num=Math.floor(Math.random()*13)+1;
            if(!playerInfo.guanjie)playerInfo.guanjie=num;
            const guanjie=ui.create.div('.guanjie',node);
            guanjie.setBackgroundImage('extension/点绛唇/image/level/guanjie_icon_'+playerInfo.guanjie+'.png');
            
            const handCardsBg=ui.create.div('.handCardsBg',node);
            ui.create.div('.handCard',handCardsBg,function(){
                game.openCardsDialog(playerInfo);
            });
            if (isSecond) {
                const dataData = ui.create.div('.dataData', node);
                let kills=0;
                for(let evt of playerInfo.stat){
                    if(evt.kill)kills+=evt.kill;
                };
                let gains=0;
                playerInfo.getAllHistory('gain',evt=>{
                    gains+=evt.cards.length;
                });
                const useCards=playerInfo.getAllHistory('useCard').length+playerInfo.getAllHistory('respond').length;
                let damageEvents = 0;
                let recoverEvents = 0;
                game.getAllGlobalHistory('changeHp', evt => {
                    if(evt.getParent().source && evt.getParent().source === playerInfo){
                        if(evt.getParent().name == 'recover')recoverEvents+=evt.getParent().num;
                        else if(evt.getParent().name=='damage')damageEvents+=evt.getParent().num;
                    };
                });
                const dataItems = [
                    '击杀数:' + kills,
                    '摸牌数:' + gains,
                    '用牌数:' + useCards,
                    '造成伤害:' + damageEvents,
                    '治疗量:' + recoverEvents
                ];
            
                for (let name of dataItems) {
                    ui.create.div('.dataText', name, dataData);
                }
            }
        };
        
        let winnersBg = null;
        let losersBg = null;
        let dataBg=null;
        
        function clearBackgrounds() {
            [winnersBg, losersBg, dataBg].forEach(element => {
                if(element){
                    element.delete();
                    element = null;
                };
            });
        }
        
        function updateFirst() {//初始页面
            clearBackgrounds(); // 清除旧的背景元素
            
            const modeType = lib.config.all.mode.find(mode => lib.configOL[mode+'_mode'] || (mode !== 'connect' && lib.config.mode === mode));
            modetop.innerHTML = lib.translate[modeType] || '未知模式';
            
            winnersBg = ui.create.div('.winnersBg', mvpBg);
            losersBg = ui.create.div('.losersBg', mvpBg);
            
            winners.forEach(player => createPlayerEntry(winnersBg, player, true));
            losers.forEach(player => createPlayerEntry(losersBg, player));
        }
        
        function updateSecond() {//战绩数据页面
            clearBackgrounds();
            
            modetop.innerHTML = '对局数据详情';
            
            dataBg=ui.create.div('.dataBg',mvpBg);
            winners.forEach(player => createPlayerEntry(dataBg, player, true,true));
            losers.forEach(player => createPlayerEntry(dataBg, player,null,true));
        }
        
        updateFirst();
	};
	
    lib.onover.push(function(bool) {
        if(!lib.config.extension_点绛唇_overMvp)return;
        ui.dialogs[0]&&ui.dialogs[0].hide();
        
        // 胜负判定
        const addToWinner = character => {
            winner.push(character);
        };
        const processCharacters = characters => {
            characters.forEach(character => addToWinner(character));
        };
        const winner = [];
        
        const zhu = game.zhu;
        if (zhu) {
            if (zhu.isAlive()) {
                addToWinner(zhu);
                processCharacters(zhu.getFriends(null, true));
            } else {
                const nei = game.filterPlayer2(p => !p.getFriends(null, true).length);
                const hasOther = game.filterPlayer(p => !nei.includes(p) && p !== zhu).length;
    
                if (nei.length) {
                    if (!hasOther) {
                        processCharacters(nei.filter(p => p.isAlive()));
                    } else {
                        processCharacters(zhu.getEnemies(null, true).filter(p => !nei.includes(p)));
                    }
                } else {
                    processCharacters(zhu.getEnemies(null, true));
                }
            }
        } else {
            if (bool === true) {
                addToWinner(game.me);
                processCharacters(game.me.getFriends(null, true));
            } else if (bool === false) {
                const alive = game.filterPlayer();
                const target = alive.length === 1 ? alive[0] : alive[0].getEnemies(null, false).length ? game.me : alive[0];
    
                addToWinner(target);
                processCharacters(target.getFriends(null, true));
            }
        };
        
        const loser=game.filterPlayer2(current=>!winner.includes(current));
        
        //mvp分计算
        let maxMvpPlayer = game.me;
        let maxMvpScore = -Infinity;
        game.filterPlayer2(current => {
            let damageEvents = 0;
            let recoverEvents=0;
            game.getAllGlobalHistory('changeHp', evt => {
                    if(evt.getParent().source && evt.getParent().source === current){
                        if(evt.getParent().name == 'recover')recoverEvents+=evt.getParent().num;
                        else if(evt.getParent().name=='damage')damageEvents+=evt.getParent().num;
                    };
                });
            let kills=0;
            for(let evt of current.stat){
                if(evt.kill)kills+=evt.kill;
            };
            let gains=0;
            current.getAllHistory('gain',evt=>{
                gains+=evt.cards.length;
            });
            const useCards = current.getAllHistory('useCard').length;
            const responds = current.getAllHistory('respond').length;
            let mvpCount = (damageEvents+recoverEvents)*2 + kills*10+Math.floor((gains+useCards+responds)/ 2);
            if(winner.includes(current))mvpCount+=Math.floor(Math.pow(current.getEnemies(null,true).length,2)*1.5);

            current.mvpCount = mvpCount;

            if (mvpCount > maxMvpScore) {
                maxMvpScore = mvpCount;
                maxMvpPlayer = current;
            };
        });

        //特效播放
        let waitTime=500;
    
        const isDraw = bool !== true && bool !== false;
        const modeType = lib.config.all.mode.find(mode => lib.configOL[mode+'_mode'] || (mode !== 'connect' && lib.config.mode === mode));
        let effectPath;
        const options = { scale: 0.75 };
        
        if (modeType === 'doudizhu') {
            effectPath = bool==true ? winnerEffects.doudizhu.win : winnerEffects.doudizhu.lose;
            if (isDraw) options.action = 'play3';
        }
        else if (modeType === 'identity') {
            if (bool==true) {
                if (!['zhu','zhong'].includes(game.me.identity)) {
                    effectPath = winnerEffects.identity[game.me.identity];
                } else {
                    effectPath = winnerEffects.identity.zhuzhong;
                    options.action = game.me.identity === 'zhu' ? 'play3' : 'play';
                }
            } else {
                effectPath = winnerEffects.identity.lose;
                if (isDraw) options.action = 'play3';
            }
        } else {
            effectPath = bool==true ? winnerEffects.default.win : winnerEffects.default.lose;
            if (isDraw) options.action = 'play3';
        }
        
        if (effectPath && game.hasExtension('十周年UI')){
            waitTime = 3000;
            dcdAnim.loadSpine(effectPath,'skel',()=>{
                dcdAnim.playSpine({ name: effectPath }, options);
            });
            ui.create.control('查看胜负', function() {
                dcdAnim.playSpine({ name: effectPath }, options);
                game.playAudio('../extension/点绛唇/extension/Mvp/audio/'+(bool==true?'win':'lose')+'.mp3');
            });
        };

        //mvp页面
        game.broadcastAll((winner,loser,maxMvpPlayer,waitTime)=>{
            setTimeout(()=>{
                if(game.openMvp)game.openMvp(maxMvpPlayer,()=>{
                    game.openOverDialog(winner,loser);
                    ui.create.control('查看MVP', function() {
                        game.openMvp(maxMvpPlayer);
                    });
                    ui.create.control('对局记录', function() {
                        game.openOverDialog(winner,loser)
                    });
                });
            },waitTime);
        },winner,loser,maxMvpPlayer,waitTime);
    });